﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;

namespace MaximServices.Common
{
    public class HttpHelper
    {
        public static HttpClient Client { get; } = new HttpClient();

        public static string GetHTMLByURL(string url, out string redirectUrl)
        {
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            HttpWebResponse response = null;
            req.Proxy = null;
            req.AllowAutoRedirect = true;//禁止重定向
            req.UserAgent = "Mozilla/5.0 (compatible;Windows NT 6.1; WOW64;Trident/6.0;MSIE 9.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.27 Safari/537.36";

            response = req.GetResponse() as HttpWebResponse;

            //发生重定向就重新获取
            if (response.StatusCode == HttpStatusCode.Redirect ||
                response.StatusCode == HttpStatusCode.MovedPermanently)
            {
                return GetHTMLByURL(response.Headers["Location"], out redirectUrl);
            }

            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
            {
                redirectUrl = response.ResponseUri.AbsoluteUri;

                return reader.ReadToEnd();
            }
        }
    }
}
